
import { Input } from '@/components/ui/input';
import MenuToggle from '../components/MenuToggle';
import { Badge } from '@/components/ui/badge';
import { CardContent, CardHeader, Card, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHeader, TableRow, TableHead } from '@/components/ui/table';
import { SelectItem, Select, SelectContent, SelectValue, SelectTrigger } from '@/components/ui/select';
import { Pause, User, RotateCcw, CheckCircle, FileText, Clock, Eye, Play, Filter, Search, X, AlertCircle, XCircle } from 'lucide-react';
import React, { useState } from 'react';
import { DialogContent, DialogTitle, Dialog, DialogHeader, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
const WorkflowInstance = ({ toggleSidebar }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [filterWorkflow, setFilterWorkflow] = useState('all');
  const [selectedInstance, setSelectedInstance] = useState(null);

  // 模拟工作流实例数据
  const instances = [
    {
      id: 'WF-2024-001',
      workflowName: '用户注册审批流程',
      workflowId: 1,
      status: 'completed',
      startTime: '2024-01-20 14:30:25',
      endTime: '2024-01-20 14:35:12',
      duration: '4分47秒',
      initiator: '张三',
      currentNode: '流程结束',
      progress: 100,
      nodes: [
        { name: '提交申请', status: 'completed', startTime: '14:30:25', endTime: '14:30:26' },
        { name: '自动验证', status: 'completed', startTime: '14:30:26', endTime: '14:31:15' },
        { name: '人工审核', status: 'completed', startTime: '14:31:15', endTime: '14:34:30' },
        { name: '发送通知', status: 'completed', startTime: '14:34:30', endTime: '14:35:12' }
      ]
    },
    {
      id: 'WF-2024-002',
      workflowName: '文件上传处理流程',
      workflowId: 2,
      status: 'running',
      startTime: '2024-01-20 15:20:10',
      endTime: null,
      duration: '进行中',
      initiator: '李四',
      currentNode: '病毒扫描',
      progress: 60,
      nodes: [
        { name: '文件接收', status: 'completed', startTime: '15:20:10', endTime: '15:20:11' },
        { name: '格式验证', status: 'completed', startTime: '15:20:11', endTime: '15:20:45' },
        { name: '病毒扫描', status: 'running', startTime: '15:20:45', endTime: null },
        { name: '文件存储', status: 'pending', startTime: null, endTime: null },
        { name: '生成缩略图', status: 'pending', startTime: null, endTime: null }
      ]
    },
    {
      id: 'WF-2024-003',
      workflowName: '异常处理流程',
      workflowId: 5,
      status: 'failed',
      startTime: '2024-01-20 13:15:30',
      endTime: '2024-01-20 13:18:45',
      duration: '3分15秒',
      initiator: '系统',
      currentNode: '异常分析',
      progress: 40,
      nodes: [
        { name: '异常检测', status: 'completed', startTime: '13:15:30', endTime: '13:16:00' },
        { name: '异常分析', status: 'failed', startTime: '13:16:00', endTime: '13:18:45' },
        { name: '自动修复', status: 'skipped', startTime: null, endTime: null },
        { name: '通知管理员', status: 'pending', startTime: null, endTime: null }
      ]
    },
    {
      id: 'WF-2024-004',
      workflowName: '数据备份流程',
      workflowId: 4,
      status: 'paused',
      startTime: '2024-01-20 12:00:00',
      endTime: null,
      duration: '已暂停',
      initiator: '定时任务',
      currentNode: '数据压缩',
      progress: 75,
      nodes: [
        { name: '数据收集', status: 'completed', startTime: '12:00:00', endTime: '12:15:30' },
        { name: '数据验证', status: 'completed', startTime: '12:15:30', endTime: '12:20:15' },
        { name: '数据压缩', status: 'paused', startTime: '12:20:15', endTime: null },
        { name: '上传备份', status: 'pending', startTime: null, endTime: null }
      ]
    },
    {
      id: 'WF-2024-005',
      workflowName: '用户注册审批流程',
      workflowId: 1,
      status: 'cancelled',
      startTime: '2024-01-20 11:45:20',
      endTime: '2024-01-20 11:47:10',
      duration: '1分50秒',
      initiator: '王五',
      currentNode: '人工审核',
      progress: 50,
      nodes: [
        { name: '提交申请', status: 'completed', startTime: '11:45:20', endTime: '11:45:21' },
        { name: '自动验证', status: 'completed', startTime: '11:45:21', endTime: '11:46:05' },
        { name: '人工审核', status: 'cancelled', startTime: '11:46:05', endTime: '11:47:10' },
        { name: '发送通知', status: 'skipped', startTime: null, endTime: null }
      ]
    }
  ];

  // 工作流列表
  const workflows = [
    { id: 1, name: '用户注册审批流程' },
    { id: 2, name: '文件上传处理流程' },
    { id: 4, name: '数据备份流程' },
    { id: 5, name: '异常处理流程' }
  ];

  // 过滤实例数据
  const filteredInstances = instances.filter(instance => {
    const matchesSearch = instance.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         instance.workflowName.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         instance.initiator.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = filterStatus === 'all' || instance.status === filterStatus;
    const matchesWorkflow = filterWorkflow === 'all' || instance.workflowId.toString() === filterWorkflow;
    return matchesSearch && matchesStatus && matchesWorkflow;
  });

  const getStatusBadge = (status) => {
    const statusConfig = {
      running: { color: 'bg-blue-100 text-blue-800', text: '运行中' },
      completed: { color: 'bg-green-100 text-green-800', text: '已完成' },
      failed: { color: 'bg-red-100 text-red-800', text: '失败' },
      paused: { color: 'bg-yellow-100 text-yellow-800', text: '已暂停' },
      cancelled: { color: 'bg-gray-100 text-gray-800', text: '已取消' }
    };
    
    const config = statusConfig[status] || statusConfig.running;
    return (
      <Badge className={`${config.color} hover:${config.color}`}>
        {config.text}
      </Badge>
    );
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'running':
        return <Play className="w-5 h-5 text-blue-600" />;
      case 'completed':
        return <CheckCircle className="w-5 h-5 text-green-600" />;
      case 'failed':
        return <XCircle className="w-5 h-5 text-red-600" />;
      case 'paused':
        return <Pause className="w-5 h-5 text-yellow-600" />;
      case 'cancelled':
        return <X className="w-5 h-5 text-gray-600" />;
      default:
        return <Clock className="w-5 h-5 text-gray-600" />;
    }
  };

  const getNodeStatusIcon = (status) => {
    switch (status) {
      case 'completed':
        return <CheckCircle className="w-4 h-4 text-green-600" />;
      case 'running':
        return <Play className="w-4 h-4 text-blue-600" />;
      case 'failed':
        return <XCircle className="w-4 h-4 text-red-600" />;
      case 'paused':
        return <Pause className="w-4 h-4 text-yellow-600" />;
      case 'cancelled':
        return <X className="w-4 h-4 text-gray-600" />;
      case 'skipped':
        return <AlertCircle className="w-4 h-4 text-gray-400" />;
      default:
        return <Clock className="w-4 h-4 text-gray-400" />;
    }
  };

  const runningCount = instances.filter(i => i.status === 'running').length;
  const completedCount = instances.filter(i => i.status === 'completed').length;
  const failedCount = instances.filter(i => i.status === 'failed').length;
  const pausedCount = instances.filter(i => i.status === 'paused').length;

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-xl flex items-center justify-center">
                  <FileText className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    流程实例
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    查看和管理工作流执行实例
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：搜索和筛选 */}
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <input
                  type="text"
                  placeholder="搜索实例..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 pr-4 py-2 w-80 border border-material-grey-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
                />
              </div>

              <Select value={filterWorkflow} onValueChange={setFilterWorkflow}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="选择工作流" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部工作流</SelectItem>
                  {workflows.map(workflow => (
                    <SelectItem key={workflow.id} value={workflow.id.toString()}>
                      {workflow.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-32">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="running">运行中</SelectItem>
                  <SelectItem value="completed">已完成</SelectItem>
                  <SelectItem value="failed">失败</SelectItem>
                  <SelectItem value="paused">已暂停</SelectItem>
                  <SelectItem value="cancelled">已取消</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">运行中</p>
                  <p className="text-2xl font-bold text-blue-600">{runningCount}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Play className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">已完成</p>
                  <p className="text-2xl font-bold text-green-600">{completedCount}</p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <CheckCircle className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">失败</p>
                  <p className="text-2xl font-bold text-red-600">{failedCount}</p>
                </div>
                <div className="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                  <XCircle className="w-6 h-6 text-red-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">已暂停</p>
                  <p className="text-2xl font-bold text-yellow-600">{pausedCount}</p>
                </div>
                <div className="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                  <Pause className="w-6 h-6 text-yellow-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 实例列表 */}
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>实例信息</TableHead>
                  <TableHead>工作流</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>进度</TableHead>
                  <TableHead>发起人</TableHead>
                  <TableHead>开始时间</TableHead>
                  <TableHead>执行时长</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredInstances.map((instance) => (
                  <TableRow key={instance.id}>
                    <TableCell>
                      <div className="flex items-center space-x-3">
                        {getStatusIcon(instance.status)}
                        <div>
                          <p className="font-medium text-material-grey-900">{instance.id}</p>
                          <p className="text-sm text-material-grey-500">当前节点: {instance.currentNode}</p>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{instance.workflowName}</span>
                    </TableCell>
                    <TableCell>
                      {getStatusBadge(instance.status)}
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="flex items-center space-x-2">
                          <Progress value={instance.progress} className="w-16 h-2" />
                          <span className="text-xs text-material-grey-600">{instance.progress}%</span>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-2">
                        <User className="w-4 h-4 text-material-grey-500" />
                        <span className="text-sm text-material-grey-700">{instance.initiator}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-600">{instance.startTime}</span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-600">{instance.duration}</span>
                    </TableCell>
                    <TableCell className="text-right">
                      <Dialog>
                        <DialogTrigger asChild>
                          <Button 
                            variant="ghost" 
                            size="sm"
                            onClick={() => setSelectedInstance(instance)}
                          >
                            <Eye className="w-4 h-4 mr-2" />
                            查看详情
                          </Button>
                        </DialogTrigger>
                        <DialogContent className="sm:max-w-2xl">
                          <DialogHeader>
                            <DialogTitle>实例详情 - {selectedInstance?.id}</DialogTitle>
                          </DialogHeader>
                          {selectedInstance && (
                            <div className="space-y-6">
                              {/* 基本信息 */}
                              <div className="grid grid-cols-2 gap-4">
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">工作流名称</label>
                                  <p className="text-material-grey-900">{selectedInstance.workflowName}</p>
                                </div>
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">实例状态</label>
                                  <div className="mt-1">{getStatusBadge(selectedInstance.status)}</div>
                                </div>
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">发起人</label>
                                  <p className="text-material-grey-900">{selectedInstance.initiator}</p>
                                </div>
                                <div>
                                  <label className="text-sm font-medium text-material-grey-600">执行进度</label>
                                  <div className="flex items-center space-x-2 mt-1">
                                    <Progress value={selectedInstance.progress} className="flex-1 h-2" />
                                    <span className="text-sm text-material-grey-600">{selectedInstance.progress}%</span>
                                  </div>
                                </div>
                              </div>

                              {/* 执行节点 */}
                              <div>
                                <h4 className="text-lg font-medium text-material-grey-900 mb-4">执行节点</h4>
                                <div className="space-y-3">
                                  {selectedInstance.nodes.map((node, index) => (
                                    <div key={index} className="flex items-center space-x-4 p-3 bg-material-grey-50 rounded-lg">
                                      {getNodeStatusIcon(node.status)}
                                      <div className="flex-1">
                                        <div className="flex items-center justify-between">
                                          <span className="font-medium text-material-grey-900">{node.name}</span>
                                          <span className="text-xs text-material-grey-500">
                                            {node.status === 'completed' && node.endTime && 
                                              `${node.startTime} - ${node.endTime}`}
                                            {node.status === 'running' && node.startTime && 
                                              `开始于 ${node.startTime}`}
                                            {node.status === 'pending' && '等待执行'}
                                            {node.status === 'skipped' && '已跳过'}
                                          </span>
                                        </div>
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            </div>
                          )}
                        </DialogContent>
                      </Dialog>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>

            {filteredInstances.length === 0 && (
              <div className="text-center py-12">
                <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                  <FileText className="w-8 h-8 text-material-grey-500" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  {searchQuery ? '未找到匹配的实例' : '暂无流程实例'}
                </h3>
                <p className="text-material-grey-500">
                  {searchQuery ? '尝试使用不同的关键词搜索' : '当有工作流执行时，实例将显示在这里'}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </>
  );
};

export default WorkflowInstance;
